package com.iplant.aps.serviceimpl.dao.wms;

import com.iplant.aps.service.mesenum.MESDBSource;
import com.iplant.aps.service.mesenum.MESException;
import com.iplant.aps.service.po.OutResult;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.po.wms.WMSInventoryCheck;
import com.iplant.aps.service.utils.StringUtils;
import com.iplant.aps.serviceimpl.dao.BaseDAO;
import com.iplant.aps.serviceimpl.utils.aps.APSConstans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.text.MessageFormat;
import java.util.*;

public class WMSInventoryCheckDAO extends BaseDAO {

    private static final Logger logger = LoggerFactory.getLogger(WMSInventoryCheckDAO.class);

    private static WMSInventoryCheckDAO Instance = null;

    private WMSInventoryCheckDAO() {
        super();
    }

    public static WMSInventoryCheckDAO getInstance() {
        if (Instance == null)
            Instance = new WMSInventoryCheckDAO();
        return Instance;
    }

    /**
     * 添加或修改
     */
    public int Update(BMSEmployee wLoginUser, WMSInventoryCheck wWMSInventoryCheck, OutResult<Integer> wErrorCode) {
        int wResult = 0;
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wWMSInventoryCheck == null)
                return 0;

            String wSQL = "";
            if (wWMSInventoryCheck.getID() <= 0) {
                wSQL = MessageFormat.format("INSERT INTO {0}.wms_inventorycheck(LineEdgeID,MaterialID,CreateID," +
                                "CreateTime,BeforeFQTY,AfterFQTY,Type,Active) VALUES(:LineEdgeID,:MaterialID," +
                                ":CreateID,:CreateTime,:BeforeFQTY,:AfterFQTY,:Type,:Active);",
                        wInstance.Result);
            } else {
                wSQL = MessageFormat.format("UPDATE {0}.wms_inventorycheck SET LineEdgeID = :LineEdgeID,MaterialID = " +
                                ":MaterialID,CreateID = :CreateID,CreateTime = :CreateTime,BeforeFQTY = :BeforeFQTY," +
                                "AfterFQTY = :AfterFQTY,Type = :Type,Active = :Active WHERE ID = :ID;",
                        wInstance.Result);
            }

            wSQL = this.DMLChange(wSQL);

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("ID", wWMSInventoryCheck.ID);
            wParamMap.put("LineEdgeID", wWMSInventoryCheck.LineEdgeID);
            wParamMap.put("MaterialID", wWMSInventoryCheck.MaterialID);
            wParamMap.put("CreateID", wWMSInventoryCheck.CreateID);
            wParamMap.put("CreateTime", wWMSInventoryCheck.CreateTime);
            wParamMap.put("BeforeFQTY", wWMSInventoryCheck.BeforeFQTY);
            wParamMap.put("AfterFQTY", wWMSInventoryCheck.AfterFQTY);
            wParamMap.put("Type", wWMSInventoryCheck.Type);
            wParamMap.put("Active", wWMSInventoryCheck.Active);

            KeyHolder keyHolder = new GeneratedKeyHolder();
            SqlParameterSource wSqlParameterSource = new MapSqlParameterSource(wParamMap);

            shrisJdbcTemplate.update(wSQL, wSqlParameterSource, keyHolder);

            if (wWMSInventoryCheck.getID() <= 0) {
                wResult = Objects.requireNonNull(keyHolder.getKey()).intValue();
                wWMSInventoryCheck.setID(wResult);
            } else {
                wResult = wWMSInventoryCheck.getID();
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 删除集合
     */
    public ServiceResult<Integer> DeleteList(BMSEmployee wLoginUser, List<WMSInventoryCheck> wList,
                                             OutResult<Integer> wErrorCode) {
        ServiceResult<Integer> wResult = new ServiceResult<Integer>(0);
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wList == null || wList.size() <= 0)
                return wResult;

            List<String> wIDList = new ArrayList<String>();
            for (WMSInventoryCheck wItem : wList) {
                wIDList.add(String.valueOf(wItem.ID));
            }
            String wSql = MessageFormat.format("delete from {1}.wms_inventorycheck WHERE ID IN({0}) ;",
                    String.join(",", wIDList), wInstance.Result);
            this.ExecuteSqlTransaction(wSql);
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 查单条
     */
    public WMSInventoryCheck SelectByID(BMSEmployee wLoginUser, int wID, OutResult<Integer> wErrorCode) {
        WMSInventoryCheck wResult = new WMSInventoryCheck();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            List<WMSInventoryCheck> wList = SelectList(wLoginUser, wID, -1, -1, -1, -1, wErrorCode);
            if (wList == null || wList.size() != 1)
                return wResult;
            wResult = wList.get(0);
        } catch (Exception e) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(e.toString());
        }
        return wResult;
    }

    /**
     * 条件查询集合
     */
    public List<WMSInventoryCheck> SelectList(BMSEmployee wLoginUser, int wID, int wLineEdgeID, int wCreateID,
                                              int wType, int wActive, OutResult<Integer> wErrorCode) {
        List<WMSInventoryCheck> wResultList = new ArrayList<WMSInventoryCheck>();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResultList;
            }

            String wSQL = MessageFormat.format(
                    "SELECT * FROM {0}.wms_inventorycheck WHERE  1=1  and ( :wID <= 0 or :wID = ID ) and ( " +
                            ":wLineEdgeID <= 0 or :wLineEdgeID = LineEdgeID ) and ( :wCreateID <= 0 or :wCreateID = " +
                            "CreateID ) and ( :wType <= 0 or :wType = Type ) and ( :wActive <= 0 or :wActive = Active" +
                            " );",
                    wInstance.Result);

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wID", wID);
            wParamMap.put("wLineEdgeID", wLineEdgeID);
            wParamMap.put("wCreateID", wCreateID);
            wParamMap.put("wType", wType);
            wParamMap.put("wActive", wActive);

            wSQL = this.DMLChange(wSQL);

            List<Map<String, Object>> wQueryResult = shrisJdbcTemplate.queryForList(wSQL, wParamMap);

            for (Map<String, Object> wReader : wQueryResult) {
                WMSInventoryCheck wItem = new WMSInventoryCheck();

                wItem.ID = StringUtils.parseInt(wReader.get("ID"));
                wItem.LineEdgeID = StringUtils.parseInt(wReader.get("LineEdgeID"));
                wItem.MaterialID = StringUtils.parseInt(wReader.get("MaterialID"));
                wItem.CreateID = StringUtils.parseInt(wReader.get("CreateID"));
                wItem.CreateTime = StringUtils.parseCalendar(wReader.get("CreateTime"));
                wItem.BeforeFQTY = StringUtils.parseDouble(wReader.get("BeforeFQTY"));
                wItem.AfterFQTY = StringUtils.parseDouble(wReader.get("AfterFQTY"));
                wItem.Type = StringUtils.parseInt(wReader.get("Type"));
                wItem.Active = StringUtils.parseInt(wReader.get("Active"));

                wItem.Creator = APSConstans.GetBMSEmployeeName(wItem.CreateID);

                wResultList.add(wItem);
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResultList;
    }
}
